<?php

namespace App\Models;

use App\Cost\Price;
use App\Enums\OrderItemType;
use App\Enums\TableStatus;
use Carbon\Carbon;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Support\Facades\DB;

class Table extends Model
{
    use HasFactory;

    use SoftDeletes;

    protected $fillable = [
        'sort', 'name', 'people_count', 'type_id', 'status', 'use_start_at', 'table_order_id',
        'alert_date', 'alert_marked', 'is_pause',
    ];

    protected $casts = [
        'status' => TableStatus::class,
        'alert_date' => 'datetime',
        'alert_marked' => 'boolean',
        'is_pause' => 'boolean',
    ];

//    protected function serializeDate(\DateTimeInterface $date)
//    {
//        return $date->format('Y-m-d H:i:s');
//    }

    public function tableType()
    {
        return $this->belongsTo(TableType::class, 'type_id');
    }

    public function tableOrder()
    {
        return $this->belongsTo(Order::class, 'table_order_id');
    }

    public function repairLogs()
    {
        return $this->hasMany(TableRepairLog::class);
    }

    public function getQRLink()
    {
        return env("QR_TABLE_LINK").$this->id;
    }

    /**
     * @return OrderItem
     */
    public function getOrderTableItem()
    {
        return $this->tableOrder->items()->where('type', OrderItemType::Table)->first();
    }

    /**
     * @param $finishDate
     * @return Price
     */
    public function getTablePrice($finishDate)
    {
        if (empty($this->table_order_id))
            return new Price();

        $tableItem = $this->getOrderTableItem();

        return $tableItem->getPrice($finishDate);
    }

    /**
     * @param $finishDate
     * @return float|int
     */
    public function getTableTotalMoney($finishDate)
    {
        $tablePrice = $this->getTablePrice($finishDate);

        return ($tablePrice->basePrice + $tablePrice->timeOutPrice) / 100;
    }

    public function getTableTotalMinutes($finishDate)
    {
        $orderItem = $this->getOrderTableItem();
        return $orderItem->getTotalMinutes($finishDate);
    }

    public function getName()
    {
        return $this->name ?? $this->tableType->name . $this->sort;
    }

    public function pause()
    {
        DB::transaction(function () {

            $this->is_pause = true;
            $this->save();

            if (!empty($this->tableOrder)) {
                $this->tableOrder->pause();
            }
        });

        return $this;
    }

    public function unpause()
    {
        DB::transaction(function () {

            $this->is_pause = false;
            $this->save();

            if (!empty($this->tableOrder)) {
                $this->tableOrder->unpause();
            }
        });

        return $this;
    }
}
